<template>
    <el-card shadow="never" class="border-0">

      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
  
      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="审核人" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.approvers }}
          </template>
        </el-table-column>
  
        <el-table-column label="最大审批时间" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.maxApprovalTime }}
          </template>
        </el-table-column>

        <el-table-column label="审批类型" align="center">
          <template #default="{ row }">
            {{ row.approvalType==1?"或签":"会签" }}
          </template>
        </el-table-column>

        <el-table-column label="创建人" align="center">
          <template #default="{ row }">
            {{ row.createUserName }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
            <div v-else>
                <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>

                <el-popconfirm title="是否要删除该审批节点吗？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="clickDeleteBtn(scope.row.id)">
                    <template #reference>
                        <el-button text type="primary" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
          @current-change="initTableData" />
      </div>
  
      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
  
        <el-form :model="form" ref="formRef" :rules="rules" label-width="140px" :inline="false">
          
          <el-form-item label="审批人" prop="approvalId">
              <el-button>审批人</el-button>
          </el-form-item>

          <el-form-item label="审批类型" prop="approvalType">
            <el-select style="width: 100%;" v-model="form.approvalType" placeholder="审批类型">
                <el-option label="或签" value="1"></el-option>
                <el-option label="会签" value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="最大审批时间(时)" prop="maxApprovalTime">
            <el-input v-model="form.maxApprovalTime" placeholder="最大审批时间(时)" type="text" @input="(v)=>(form.maxApprovalTime=v.replace(/[^\d]/g,''))" />
          </el-form-item>

        </el-form>

      </FormDrawer>
    </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue"
import {toast,toastWarn} from "~/composables/util"
import { dateFormatter } from '~/utils/common.js'
import { getApprovalTemplateList,addApprovalTemplate,updateApprovalTemplate } from "~/api/approvalApi"

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

// 查询条件
const searchForm = reactive({
  page: currentPage.value,
  size: limit.value,
})

// 重置搜索框
const resetSearchForm = () => {
  initTableData()
}

// 表格数据
const tableData = ref([])
const loading = ref(false)


// 生命周期函数
onMounted(() => {
  //初始化列表数据
  initTableData()
})


// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  getApprovalTemplateList(searchForm)
    .then(res => {
       if(res && res.records){
          tableData.value = res.records      
          total.value = res.total
        }else{
          tableData.value = []  
          total.value = 0
        }
    })
    .finally(() => {
      loading.value = false
    })
}

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
  approvalType: null,
  maxApprovalTime: null
})
//执行表单校验
const rules = {
  approvalType: [
    { required: true, message: '审批类型不能为空', trigger: 'change' }
  ],
  maxApprovalTime: [
    { required: true, message: '最大审批时间不能为空', trigger: 'change' }
  ]
}

//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //loading
        formDrawerRef.value.showLoading()
        //根据是否是修改标记，判断执行新增接口还是修改接口
        const fun = editId.value ? updateApprovalTemplate(editId.value, form) : addApprovalTemplate(form)
        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            initTableData(editId.value ? false : 1)
            formDrawerRef.value.close()
        })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
    })
}

// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}

// 新增按钮点击事件
const handleCreate = () => {
  //修改标记置为0
  editId.value = 0
  resetForm({
    approvalType: null,
    maxApprovalTime: null
  })
  //打开弹窗
  formDrawerRef.value.open()
}

// 编辑
const handleEdit = (row) => {
  editId.value = row.templateId
  resetForm(row)
  formDrawerRef.value.open()
}

// 删除
const clickDeleteBtn = (id) => {
  loading.value = true
  deleteCompany(id).then(res => {
      toast("删除成功")
      initTableData()
  })
  .finally(() => {
      loading.value = false
  })
}


const addNode = () => {
    form.nodes.push({ approverId: '', maxApprovalTime: '', approvalType: '' })
}

const removeNode = (index) => {
    form.nodes.splice(index, 1)
}

</script>